package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.config.security.JwtTokenUtil;
import com.example.entity.Role;
import com.example.mapper.AdminMapper;
import com.example.entity.Admin;
import com.example.entity.RespBean;
import com.example.mapper.RoleMapper;
import com.example.service.IAdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author liu
 * @since 2022-01-27
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {

    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Autowired
    private RoleMapper roleMapper;


    @Override
    public RespBean login(String username, String password, String code, HttpServletRequest request) {
//        System.out.println("//////:::::");
//        System.out.println(username + password + code);

        //验证码校验
        String captcha = (String) request.getSession().getAttribute("captcha_1");
//        System.out.println("AdminServiceImpl的captcha为:" + captcha);
        if(StringUtils.isEmpty(code) || !captcha.equalsIgnoreCase(code)){
            return RespBean.error("验证码输入错误，请重新输入！");
        }
//        System.out.println("++++++++++++++");

        //登录
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
//        System.out.println("+++++++" + userDetails.getUsername());
//        System.out.println("password: "+ password + "userDetails.getPassword: " + userDetails.getPassword());
//        System.out.println("userid is == " + userDetails.g);
//        System.out.println("userDetailsService.loadUserByUsername(username) is "+userDetailsService.loadUserByUsername(username));
        if(userDetailsService.loadUserByUsername(username) == null){
//            throw new UsernameNotFoundException("用户名不存在或密码不正确");
            return RespBean.error("用户名不存在或账号未启用");
        }
//        if(!userDetails.isEnabled()){
////            throw new UsernameNotFoundException("用户名不存在或密码不正确");
//            return RespBean.error("账号被禁用，请联系管理员");
//        }
        if(!passwordEncoder.matches(password,userDetails.getPassword())){
//            throw new UsernameNotFoundException("用户名不存在或密码不正确");
            return RespBean.error("用户名或密码不正确");
        }



        //更新security登录用户对象
        UsernamePasswordAuthenticationToken authenticationToken = new
                UsernamePasswordAuthenticationToken(userDetails,
                null,userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        //生成token
        String token = jwtTokenUtil.generateToken(userDetails);
        Map<String ,String> tokenMap = new HashMap<>();
        tokenMap.put("token",token);
        tokenMap.put("tokenHead",tokenHead);

        return RespBean.success("登录成功",tokenMap);
    }


    /**
     * 根据用户名获取用户
     * @param username
     * @return
     */
    @Override
    public Admin getAdminByUserName(String username) {

        return adminMapper.selectOne(new QueryWrapper<Admin>().eq("username",username)
                .eq("enabled",true));
    }

    /**
     * 更新用户密码
     * @param oldPass
     * @param newPass
     * @param adminId
     * @return
     */

    @Override
    public RespBean updateAdminPassword(String oldPass, String newPass, Integer adminId) {
        Admin admin = adminMapper.selectById(adminId);
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        if(bCryptPasswordEncoder.matches(oldPass,admin.getPassword())){
            admin.setPassword(bCryptPasswordEncoder.encode(newPass));
            int result = adminMapper.updateById(admin);
            if(result==1){
                return RespBean.success("更新成功");
            }
        }else {
            return RespBean.error("旧密码有误，请重新输入！");
        }
       return RespBean.success("");
    }

    /**
     * 更新用户头像
     * @param url
     * @param id
     * @param authentication
     * @return
     */
    @Override
    public RespBean updateAdminUserFace(String url, Integer id, Authentication authentication) {
        Admin admin = adminMapper.selectById(id);
        admin.setUser_face(url);
        int result = adminMapper.updateById(admin);
        if(1==result){
            Admin principal =(Admin)authentication.getPrincipal();
            principal.setUser_face(url);
            SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(authentication,null,authentication.getAuthorities()));
            return RespBean.success("更新成功",url);
        }
        return RespBean.error("更新失败");
    }

    @Override
    public List<Role> getRoles(Integer adminId) {
        return roleMapper.getRoles(adminId);
    }
}

